package cn.edu.bjut.homework.chapter7;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CardLayoutTester implements ActionListener {
	private JFrame frm;
	private JButton btnPrevious, btnNext, btnLast, btnFirst; 
	private JPanel panelCard; 
	private CardLayout cardLayout; 

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					CardLayoutTester window = new CardLayoutTester();
					window.frm.setVisible(true);
					window.frm.pack();
					window.frm.setLocationRelativeTo(null);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public CardLayoutTester() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frm = new JFrame();
		frm.setTitle("CardLayout布局");
		frm.setBounds(100, 100, 450, 300);
		frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frm.getContentPane().setLayout(new BorderLayout(0, 0));
		
		JPanel panelControl = new JPanel();
		frm.getContentPane().add(panelControl, BorderLayout.SOUTH);
		panelControl.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		
		panelCard = new JPanel();
		frm.getContentPane().add(panelCard, BorderLayout.CENTER);
		cardLayout = new CardLayout(0, 0); 
		panelCard.setLayout(cardLayout);
		
		JButton[] buttons = new JButton[10]; 
		for (int i = 0; i < buttons.length; i++) {
			buttons[i] = new JButton("第" + String.valueOf(i) + "个按钮"); 
			panelCard.add(buttons[i]); 
		}
		
		btnFirst = new JButton("第一张");
		btnFirst.addActionListener(this);
		panelControl.add(btnFirst);
		
		btnPrevious = new JButton("上一张");
		btnPrevious.addActionListener(this);
		panelControl.add(btnPrevious);
		
		btnNext = new JButton("下一张");
		btnNext.addActionListener(this);
		panelControl.add(btnNext);
		
		btnLast = new JButton("最后一张");
		btnLast.addActionListener(this);
		panelControl.add(btnLast);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource().equals(btnFirst)) {
			cardLayout.first(panelCard);
		} else if (e.getSource().equals(btnLast)) {
			cardLayout.last(panelCard);
		} else if (e.getSource().equals(btnNext)) {
			cardLayout.next(panelCard);
		} else if (e.getSource().equals(btnPrevious)) {
			cardLayout.previous(panelCard);
		}
	}
}